package com.example.canvasinmain;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Random;

import com.google.gson.Gson;



import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class CanvasInMain extends Activity {
	
	MySurfaceView mySurfaceView;
	
	volatile boolean touched = false;
    volatile float touched_x, touched_y;
    
    
    
    String serverIP = "192.168.0.103";
    
    Handler mHandler = null;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		
	
		
		
	    mHandler = new Handler() {
	        @Override
	        public void handleMessage(Message msg) {
	            String text = (String)msg.obj;
	            
	            Log.v("NITESH",text);
	            
	            
	            
	            
	            /**
	             * 
	             * FIND HOW TO DRAW SHAPES ON DEMAND
	             * 
	             * 
	             */
	            
	            //call setText here
	        }
	};
		
		new network4().execute();
	    	
	
	/*  
	       
	       Thread t = new Thread(){
	    	   public void run(){
	    		   	    		   
	    		   Log.d("NITESH", "Network 4 execute begin");
	    			new network4().execute();
	    		   
	    		   
	    		   
	    		   
	    	   }
	    	   
	    	   
	       };
	       
	       t.start();
	       
	       network4 net4 = new network4();
			
	       
	       */
			
	       mySurfaceView = new MySurfaceView(this);
	       
	       //mySurfaceView.newShape = true;
	       
	       setContentView(mySurfaceView);
	       
	  	
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_canvas_in_main, menu);
		return true;
	}

	
	 protected void onResume() {
		  // TODO Auto-generated method stub
		  super.onResume();
		  mySurfaceView.onResumeMySurfaceView();
		 }
		 
		 @Override
		 protected void onPause() {
		  // TODO Auto-generated method stub
		  super.onPause();
		  mySurfaceView.onPauseMySurfaceView();
		 }
	
	
	
	
	
	
	
	class MySurfaceView extends SurfaceView implements Runnable{
	     
		   Thread thread = null;
		    SurfaceHolder surfaceHolder;
		    volatile boolean running = false;
		    
		    volatile boolean newShape = false;
		     
		    private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
		    Random random;
		    
		    public Handler cHandler;
		     
		    
	 
	  public MySurfaceView(Context context) {
	   super(context);
	   // TODO Auto-generated constructor stub
	   
	   
	   
	    cHandler = new Handler() {
	        @Override
	        public void handleMessage(Message msg) {
	            String text = (String)msg.obj;
	            
	            Log.v("NITESH","C HANDLER");
	            
	            newShape = true;
	            
	            
	            /**
	             * 
	             * FIND HOW TO DRAW SHAPES ON DEMAND
	             * 
	             * 
	             */
	            
	            //call setText here
	        }
	};
	   
	   
	   
	   
	   
	   
	   
	   
	   surfaceHolder = getHolder();
	   random = new Random();
	   
	   
	   
	  }
	   
	  public void onResumeMySurfaceView(){
	   running = true;
	   thread = new Thread(this);
	   thread.start();
	  }
	   
	  public void onPauseMySurfaceView(){
	   boolean retry = true;
	   running = false;
	   while(retry){
	    try {
	     thread.join();
	     retry = false;
	    } catch (InterruptedException e) {
	     // TODO Auto-generated catch block
	     e.printStackTrace();
	    }
	   }
	  }
	 
	  @Override
	  public void run() {
		  
		  
		  Canvas canvas;
	   // TODO Auto-generated method stub
	   while(running){
	    if(surfaceHolder.getSurface().isValid()){
	     canvas = surfaceHolder.lockCanvas();
	     //... actual drawing on canvas
	 
	     
	     /**
	     
	     paint.setStyle(Paint.Style.STROKE);
	        paint.setStrokeWidth(3);
	      
	     int w = canvas.getWidth();
	     int h = canvas.getHeight();
	     int x = random.nextInt(w-1); 
	     int y = random.nextInt(h-1);
	     int r = random.nextInt(255);
	     int g = random.nextInt(255);
	     int b = random.nextInt(255);
	     paint.setColor(0xff000000 + (r << 16) + (g << 8) + b);
	     canvas.drawPoint(x, y, paint);
	     
	     */
	     
	     
	     
	     
	     if(touched){
	         paint.setStrokeWidth(50);
	         paint.setColor(Color.WHITE);
	         canvas.drawPoint(touched_x, touched_y, paint);
	         
	        }
	     
	     
	     if(newShape){
	    	 
	    	 paint.setColor(Color.BLUE);
	    	 canvas.drawCircle(100, 50,20, paint);
	    	 
	    	 
	     }
	     
	     
	      
	     surfaceHolder.unlockCanvasAndPost(canvas);
	    }
	   }
	  }
	     
	   }
	
	
	  @Override
	  public boolean onTouchEvent(MotionEvent event) {
	   // TODO Auto-generated method stub
	    
	   touched_x = event.getX();
	   touched_y = event.getY();
	    
	   int action = event.getAction();
	   switch(action){
	   case MotionEvent.ACTION_DOWN:
	    touched = true;
	    break;
	   case MotionEvent.ACTION_MOVE:
	    touched = true;
	    break;
	   case MotionEvent.ACTION_UP:
	    touched = false;
	    break;
	   case MotionEvent.ACTION_CANCEL:
	    touched = false;
	    break;
	   case MotionEvent.ACTION_OUTSIDE:
	    touched = false;
	    break;
	   default:
	   }
	   return true; //processed
	  }
	  
	  
	  class network4 extends AsyncTask<Object, Integer, Object>{
	    	
	    	public Socket socket = null;
	    	public  ObjectOutputStream objectOutputStream = null;
	    	public  ObjectInputStream objectInputStream = null;
	    	
	    	//String serverIP = "192.168.0.101";
	    	int port = 4444;
	    	
	    	Gson gson = new Gson();	
	    	

		public network4(){
			Log.d("NITESH", "new network 4 created");
			
			
		}
	    		
	    		
		protected Object doInBackground(Object... params) {
			
			Log.d("NITESH", "inside network 4");
			
			/**
			 *UI calls will NOT work within try/catch
			 *RESTUCTURE THIS
			 */
			
			//lbl1.setText("network 4 successful");
			
			
			try {
				
						
				msg msgMessage = new msg("android device connected");
				String json = gson.toJson(msgMessage);
				
				
				
				
				String msgSend = "android connected";
				
				if(socket == null) {
					socket = new Socket(serverIP, 4444);
					//socket = new Socket("192.168.0.101", 4444);
					objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
					objectInputStream = new ObjectInputStream(socket.getInputStream());
					Log.v("NITESH", "connection established");
					
					
					
				}
				objectOutputStream.writeObject(json);
				//objectOutputStream.writeObject(msgSend);
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			while (objectInputStream != null) {
				
				msg message = null;
	        	//msg sendMsg = new msg("hello client");
	        	
				String str = null;
	        	
	        	try {
	        		
	        		
	        		//lbl1.setText("network 4 successful");
	        		
	        		str = (String) objectInputStream.readObject();
	        		
	        		Message msg = new Message();
	        		
	        		msg.obj = str;
	        		mHandler.sendMessage(msg);
	        		
	        		
	        		Log.v("NITESH", str + " network 4 call");
	        		
	        		
	        		Message cMsg = new Message();
	        		cMsg.obj = "Hello cHandler";
	        		
	        		mySurfaceView.cHandler.sendMessage(cMsg);
	        		
	        		
	        	}
	        	
	        	catch(Exception e){
	        		
	        		
	        	}
				
				
				
			}
			
//			try {
//				socket.close();
//				objectOutputStream.close();
//				objectInputStream.close();
//				socket = null;
//				objectInputStream = null;
//				objectOutputStream = null;
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
			
			// TODO Auto-generated method stub
			return null;
		}

		protected void onProgressUpdate(Integer... progress) {
	        
	    }

	    protected void onPostExecute(Long result) {
	        
	    }

	    
	    }
	    
	  
	  
	  
	  
	  
	  
	     
	   }
	
	
	
	



